import { Button, DatePicker, FormInstance } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ProFormFieldSet } from '@ant-design/pro-form';
import { history } from 'umi';
import StatisticsCard from '@/components/StatisticsCard/Index';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { getSupplierSaleDataForDetail, downSupplierSaleDataForDetail } from '@/services/report/api'; 
import { subtractDays, currentDate, isNull, showMsg } from '@/utils/utils';
import moment from 'moment';
import PermissionControl from '@/components/PermissionControl';
import './style.less'

const StockList: React.FC = (props) => {
  const { id = '', title = '', start, end, supplier = '', batchId = '' } = props.location.query;
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [detail, setDetail] = useState({});
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});


  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '供应商名称',
      dataIndex: 'supplier',
      width: 130,
    },
    {
      title: '批次编号',
      dataIndex: 'batchId',
      width: 120,
    },
    {
      title: '结算周期',
      dataIndex: 'rangedate',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest },form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet style={{gap: 2}}>
            <DatePicker allowClear={false} style={{width: '100%'}} />
              <span style={{padding: '0 5px'}}>-</span>
            <DatePicker allowClear={false} style={{width: '100%'}} />
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '商品编号',
      dataIndex: 'goodsId',
      width: 120,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项'
          }
        ]
      },
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 130,
    },
    {
      title: '商品规格',
      dataIndex: 'specsName',
      search: false,
      width: 130,
    },
    {
      title: '协议进货价',
      dataIndex: 'agreePrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '进货折扣',
      dataIndex: 'purchaseDiscount',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '供应商结算价',
      dataIndex: 'purchasePrice',
      width: 80,
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '订单号',
      dataIndex: 'orderId',
      width: 120,
      search: false
    },
    {
      title: '订单类型',
      dataIndex: 'goodsType',
      width: 80,
      search: false
    },
    {
      title: '数量',
      dataIndex: 'num',
      width: 80,
      align: 'right',
      search: false
    },
    {
      title: '供应商结算金额',
      dataIndex: 'totalPrice',
      width: 90,
      align: 'right',
      valueType: 'money',
      search: false
    }
  ];

  useEffect(() => {
    formRef.current?.setFieldsValue({
      rangedate: [moment(start), '-', moment(end)],
      goodsId: id,
      goodsName: title,
      supplier,
      batchId,
    });
    formRef.current?.submit();
  }, [])

  const getList = async(params: any) => {
    try {
      console.log('params', params)
      params.begin_date_str = moment(params.rangedate[0]).format('YYYYMMDD');
      params.end_date_str = moment(params.rangedate[2]).format('YYYYMMDD');
      const data = await getSupplierSaleDataForDetail(params);
      setDetail(data);
      setSearchParams(params);
      return {
        data: data.record_list,
        success: true,
        total: data.sum_record_num
      }
    } catch (error) {
      showMsg(error?.data?.errmsg); 
      return {
        data: [],
        success: true,
        total: 0
      };
    }
  }

  const download = async() => {
    setLoading(true);
    await downSupplierSaleDataForDetail(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }
  
  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} title='供应商结算详情' breadcrumb={{}} onBack={() => history.goBack()}>
      <ProTable<STOCKGOODSAPI.GoodsItem, STOCKGOODSAPI.GoodsItem & COMMON.PageParams>
        formRef={formRef}
        actionRef={actionRef}
        rowKey="goods_id"
        bordered
        manualRequest
        form={{
          ignoreRules: false
        }}
        search={{
          defaultCollapsed: false,
          collapseRender: () => { return ''},
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              ...dom,
              <PermissionControl action_id="700703004">
                <Button key="export" type="primary" loading={loading} disabled={isNull(detail.record_list)} onClick={download}>导出报表</Button>
              </PermissionControl>
            ]
          }
        }}
        options={false}
        request={getList}
        columns={columns}
        scroll={{ x : 1400 }}
        tableExtraRender={(_, data) => (
          <div className='StatisticsCard' style={{ background: '#fff', padding: 12, marginBottom: -14 }}>
            <div style={{marginBottom: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
              <StatisticsCard iconType="database" title="周期销售总量" number={detail.totalSellNum}/>
              <StatisticsCard iconType="database" title="周期退款总量" number={detail.totalRefundNum} />
              <StatisticsCard iconType="database" title="周期结算总量" number={detail.totalSettNum}/>
              <StatisticsCard style={{marginRight: 0}} title="周期结算额" number={`￥${detail.realSettPrice}`} />
            </div>
          </div>
        )}
      />
    </PageContainer>
  );
};
export default StockList;
